<?php
/**
 * Description : elasticsearch-php 链接类
 * @filename   : ElasticsearchConnect.php
 * @author     : liuqingwei
 * @date       : 2019-08-07
 *
 * @Copyright (c) 2015 liuqingwei
 *
 * vim set ts=4
 */
namespace helpers\Elasticsearch;

use common\helpers\PrintHelper;
use Elasticsearch\ClientBuilder;
use Yii;


class ElasticsearchConnect
{
    private $es;
    private static $instance;
    
    /**
     * 初始化
     * @param array $config 集群配置
     * @throws \Exception
     */
    private function __construct($config=array())
    {
        if (empty($config))
        {
            $config = Yii::$app->params['elasticsearch']['cluster_address'];
        }
        
        try {
            $this->es = ClientBuilder::create()->setHosts($config)->build();
        } catch (\Exception $e) {
            
            if (PHP_SAPI == 'cli')
            {
                PrintHelper::showLog(sprintf('cli模式-Elasticsearch链接失败原因[%s]',$e->getMessage()));
            }
            else
            {
                Yii::error(sprintf('web模式-Elasticsearch链接失败原因[%s]',$e->getMessage()));
            }
            
            return false;
        }
    }
    
    /**
     * 公共方法(获取实例)
     * @param array $config 配置
     * @return object
     * @throws \Exception
     */
    public static function getInstance($config)
    {
        if (!self::$instance instanceof self)
        {
            self::$instance = new self($config);
        }
        return self::$instance;
    }
    
    /**
     * 扩展方法
     *
     * @param string $name      方法名
     * @param array  $arguments 参数
     *
     * @return mixed
     */
    public function __call($name,$arguments)
    {
        try {
            return $this->es->$name(...$arguments);
            
        } catch (\Exception $e) {
            
            if (PHP_SAPI == 'cli')
            {
                PrintHelper::showLog(sprintf('cli模式-Elasticsearch调用失败方法[%s],参数[%s],失败原因[%s]',$name,json_encode($arguments),$e->getMessage()));
            }
            else
            {
                Yii::error(sprintf('web模式-Elasticsearch调用失败方法[%s],参数[%s],失败原因[%s]',$name,json_encode($arguments),$e->getMessage()));
            }
            
            return false;
        }
    }
}